import {
	defineStore
} from "pinia";

// ArrayBuffer转16进度字符串示例
function ab2hex(buffer) {
  const hexArr = Array.prototype.map.call(
    new Uint8Array(buffer),
    function (bit) {
      return ('00' + bit.toString(16)).slice(-2)
    }
  )
  return hexArr.join('')
}

export const BluetoothStore = defineStore("Bluetooth", {
	state: () => {
		return {
			init: false, //是否初始化蓝牙模块
			isAvailable: false, //本机蓝牙是否可用
			mList:[],//搜索到的设备列表
			connectIndex: 0,
			deviceId: null, //连接的低功耗蓝牙设备ID
			services: [], //获取蓝牙设备的所有服务
			characteristics: [], //设备特征值列表
		};
	},
	getters: {},
	actions: {
		// 连接蓝牙设备（磅秤）
		initBluetoothDevices(){
			return new Promise((resolve,reject) => {
				console.log('连接蓝牙设备')
				let that=this;
				// if(that.init == true){
				// 	resolve()
				// 	return
				// }
				uni.openBluetoothAdapter({
					success(res) {
						that.init = true
						uni.getBluetoothAdapterState({
							success(res) {
								resolve()
								console.log('获取本机蓝牙适配器状态',res)
								that.isAvailable = res.available;
								
								uni.getBluetoothDevices({
									success(res) {
										console.log('获取已搜索到的蓝牙设备',res)
										// if (res.devices[0]) {
										// 	console.log(ab2hex(res.devices[0].advertisData))
										// }
									}
								})
							},
							errorHandle: err => {
								that.errorHandle(err);
								reject()
							}
						})
					},
					complete(com){
						console.log('初始化蓝牙模块',com)
					}
				})
			})
		},
		// 开始搜寻附近的蓝牙外围设备
		startBluetoothDevicesDiscovery(){
			let that=this;
			this.initBluetoothDevices().then(()=>{
				// 以微信硬件平台的蓝牙智能灯为例，主服务的 UUID 是 FEE7。传入这个参数，只搜索主服务 UUID 为 FEE7 的设备
				uni.startBluetoothDevicesDiscovery({
					// services: ['FEE7'],
					success(res) {
						uni.showToast({
							title: '开始搜寻附近的蓝牙外围设备',
							icon: 'none'
						})
						console.log('开始搜寻附近的蓝牙外围设备',res)
						// that.mList = res
					}
				})
			})
		},
		// 停止搜寻附近的蓝牙外围设备
		stopBluetoothDevicesDiscovery(){
			uni.stopBluetoothDevicesDiscovery({
				success(res) {
					uni.showToast({
						title: '停止搜寻附近的蓝牙外围设备',
						icon: 'none'
					})
					console.log('停止搜寻附近的蓝牙外围设备',res)
				}
			})
		},
		// 连接低功耗蓝牙设备
		createBLEConnection(deviceId){
			console.log('连接低功耗蓝牙设备',deviceId)
			let that = this;
			uni.createBLEConnection({
				deviceId:deviceId,
				success(res) {
					console.log(res)
					uni.getBLEDeviceServices({
						// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
						deviceId:deviceId,
						success(res) {
							console.log('device services:', res.services)
							that.deviceId = deviceId
							that.services = res.services
							that.getBLEDeviceCharacteristics(deviceId,res.services)
							// 连接后关闭监听
							that.stopBluetoothDevicesDiscovery()
						},
						fail(err) {
							console.log('getBLEDeviceServices.err',err)
							that.errorHandle(err);
						}
					})
				},
				fail(err){
					console.log('createBLEConnection.err',err)
					that.errorHandle(err);
				}
			})
		},
		// 获取蓝牙设备某个服务中所有特征值(characteristic)
		getBLEDeviceCharacteristics(){
			let that=this;
			let index = 0;
			uni.getBLEDeviceCharacteristics({
				// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
				deviceId:that.deviceId,
				// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
				serviceId:that.services[index].uuid,
				success(res) {
					console.log('deviceCharacteristics',res.characteristics)
					that.characteristics = res.characteristics
					// 判断设备是否可读
					if(that.characteristics[index].properties.read == true){
						that.notifyBLECharacteristicValueChange()
					}
				},
				fail(err){
					that.errorHandle(err);
				}
			})
		},
		// 启用低功耗蓝牙设备特征值变化时的 notify 功能
		notifyBLECharacteristicValueChange(index = 0){
			console.log('启用低功耗蓝牙设备特征值变化时的 notify 功能')
			let that=this;
			// let index = that.connectIndex;
			// deviceId：蓝牙设备 id，serviceId：蓝牙特征值对应服务的 uuid，characteristicId：蓝牙特征值的 uuid
			console.log('serviceId:',that.services[index].uuid,'characteristicId:',that.characteristics[index].uuid)
			uni.notifyBLECharacteristicValueChange({
				state: true, // 启用 notify 功能
				deviceId: that.deviceId,
				serviceId: that.services[index].uuid,
				characteristicId: that.characteristics[index].uuid,
				success(res) {
				    console.log('监听设备发送数据成功', res.errMsg)
					//监听设备发送数据
					uni.onBLECharacteristicValueChange((res) => {
						//这是转换成ASCII码
						let str =that.ab2ascii(res.value) 
						console.log("监听成功", str)
					})
				},
				fail(res){
					console.log('notifyBLECharacteristicValueChange fail', res.errMsg)
					setTimeout(()=>{
						console.log(`第${index+1}次尝试失败...`);
						that.connectIndex++;
						that.notifyBLECharacteristicValueChange(that.connectIndex);
					},3000);
					that.errorHandle(res)
				}
			})
		},
		//根据 uuid 获取处于已连接状态的设备
		getConnectedBluetoothDevices(services = []){
			this.initBluetoothDevices().then(()=>{
				uni.getConnectedBluetoothDevices({
					services: services,
					success(res) {
						console.log('根据 uuid 获取处于已连接状态的设备',res)
					}
				})
			})
		},
		// 错误处理
		errorHandle(error){
			console.log('错误处理',error)
			let errStr='';
			switch(error.code){
				case 10000:
					errStr="未初始化蓝牙适配器";
					break;
				case 10001:
					errStr="当前蓝牙适配器不可用";
					break;
				case 10002:
					errStr="没有找到指定设备";
					break;
				case 10003:
					errStr="连接失败";
					break;
				case 10004:
					errStr="没有找到指定服务";
					break;
				case 10005:
					errStr="没有找到指定特征值";
					break;
				case 10006:
					errStr="当前连接已断开";
					break;
				case 10007:
					errStr="当前特征值不支持此操作";
					break;
				case 10008:
					errStr="其余所有系统上报的异常";
					break;
				case 10009:
					errStr="不支持 BLE";
					break;
				case 10010:
					errStr="已连接";
					break;
				case 10011:
					errStr="配对设备需要配对码";
					break;
				case 10012:
					errStr="连接超时";
					break;
				case 10013:
					errStr="连接 deviceId 为空或者是格式不正确";
					break;
				case -1:
					errStr="设备已经连接";
					break;
			}
			
			// uni.showToast({
			// 	icon: 'none',
			// 	title: errStr
			// });
			uni.showModal({
				title: errStr
			})
		}
	}
});